<?php

namespace common\models;

use common\helpers\commonApi;
use common\helpers\JwtApi;
use common\helpers\PageApi;
use common\helpers\TransformApi;
use common\helpers\UploadApi;
use common\helpers\WeChatApi;
use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "{{%user}}".
 *
 * @property int $id
 * @property string|null $openid 微信openid
 * @property string|null $unionid
 * @property string|null $nickname 昵称
 * @property string|null $headimgurl 头像地址
 * @property string|null $sex 性别
 * @property string|null $province 省
 * @property string|null $city 市
 * @property string|null $country 县
 * @property int|null $status 状态
 * @property string|null $create_time 创建时间
 * @property string|null $update_time 修改时间
 * @property string|null $extend 扩展字段
 * @property string|null $info 信息
 * @property int|null $top_level 顶级
 * @property int|null $one_level 上上级
 * @property int|null $second_level 上级
 * @property float|null $top_brokerage
 * @property float|null $one_brokerage 上上级佣金
 * @property float|null $second_brokerage 上级佣金
 * @property int|null $sub_num 下级人
 * @property string|null $phone 手机号
 * @property int|null $dis_status 分销状态
 * @property string|null $poster 海报
 * @property string|null $poster_time 海报生成时间
 */
class User extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['nickname', 'headimgurl', 'extend', 'info', 'poster'], 'string'],
            [['status', 'top_level', 'one_level', 'second_level', 'sub_num', 'dis_status'], 'integer'],
            [['create_time', 'update_time', 'poster_time'], 'safe'],
            [['top_brokerage', 'one_brokerage', 'second_brokerage'], 'number'],
            [['openid'], 'string', 'max' => 225],
            [['unionid', 'sex', 'province', 'city', 'country', 'phone'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'openid' => '微信openid',
            'unionid' => 'Unionid',
            'nickname' => '昵称',
            'headimgurl' => '头像地址',
            'sex' => '性别',
            'province' => '省',
            'city' => '市',
            'country' => '县',
            'status' => '状态',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'extend' => '扩展字段',
            'info' => '信息',
            'top_level' => '顶级',
            'one_level' => '上上级',
            'second_level' => '上级',
            'top_brokerage' => 'Top Brokerage',
            'one_brokerage' => '上上级佣金',
            'second_brokerage' => '上级佣金',
            'sub_num' => '下级人',
            'phone' => '手机号',
            'dis_status' => '分销状态',
            'poster' => '海报',
            'poster_time' => '海报生成时间',
        ];
    }

    /**
     * 获取用户html
     * @param $data
     * @param $format 0:html 1:array
     * @return array|string
     */
    public function getUserHtml($userids,$format=0)
    {
        $user = User::find()->where(['id'=>$userids])->select(['id','info','create_time'])->asArray()->all();
        $arr = [];
        foreach ($user as $datum){
            $info = json_decode($datum['info'],true);
            if ($format){
                $arr[$datum['id']] = ['avatar'=>$info['avatarUrl'],'nickname'=>$info['nickName'],'id'=>$datum['id'],'create_time'=>$datum['create_time']];
            }else{
                $arr[$datum['id']] = "<div style='width: 100px'><div><img style='width: 100px' src='{$info['avatarUrl']}' alt=''></div><div style='text-align: center'>{$info['nickName']}</div></div>";
            }
        }
        return $arr;
    }

    /**
     * 授权登录
     * @param $code
     * @param $rawData
     * @param $jwtId
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function login($code,$rawData,$jwtId,$superior)
    {
        $superiorArr =  explode('_',$superior);
        $second_level = $superior??'';
        $campus_id = '';
        if (!empty($superiorArr[0])&&$superiorArr[1]=='campus_id'&&!empty($superiorArr[1])){//校区提现绑定人
            $campus_id = $superiorArr[1];
            $second_level = '';
        }
        $config = System::applets();
        $api = new WeChatApi($config);
        $result = $api->appletsLogin($code,$rawData);
        if (!$result['success']){
            return $result;
        }
        $wechat = $result['data']['data'];
        $weappOpenid = $result['data']['openid'];
        $user = User::find()->where(['openid' => $weappOpenid])->one();
        $isAdd = 0;
        if ($user){
            if ($user->status!==1){
                return commonApi::message('禁止登陆',false);
            }
        }else{
            $user = new User();
            $user->openid = $weappOpenid;
            $user->status = 1;
            $user->unionid = $result['data']['authData']['unionid']??'';
            $user->second_level = $second_level;
            $isAdd = 1;
        }
        if (!empty($wechat['avatarUrl'])){
            $res = (new UploadApi())->oss($wechat['avatarUrl'],$weappOpenid);
            if (!$res){
                return commonApi::message('上传头像失败',false);
            }
            $wechat['avatarUrl'] = $res;
        }
        $user->headimgurl = $wechat['avatarUrl'];
        $user->info = json_encode($wechat);
        if ($user->save()!==false){
            if ($isAdd&&$user->second_level){
                $this->updateDis($user->id);
            }
            if ($campus_id){
                $campus = Campus::findOne(['id'=>$campus_id]);
                if ($campus){
                    $campus->payment_userid = $user->id;
                    $campus->save();
                }
            }
            $jwt = new JwtApi($jwtId);
            $token = $jwt->getToken($user->id);
            return commonApi::message('登陆成功',true,[
                'nickname'=>$wechat['nickName'],
                'headimgurl'=>$wechat['avatarUrl'],
                'token'=>$token,
            ]);
        }
        return commonApi::message(commonApi::getModelError($user),false);
    }

    /**
     * 获取用户信息
     * @param $userid
     * @return array
     */
    public function getInfo($userid)
    {
        $user = self::find()->where(['id'=>$userid])->one();
        $dis = Dis::find()->where(['userid'=>$userid])->select(['status','review_status','can_brokerage'])->asArray()->one();
        $info = json_decode($user->info,true);
        $running = (new Running())->isRunn($userid);
        $coupon = UserCoupon::find()->where(['userid'=>$userid,'status'=>1,'delete'=>0])->count();
        $data = [
            'headimgurl'=>$user->headimgurl,
            'nickname'=>$info['nickName']??'',
            'dis_status'=>$user->dis_status??0,
            'dis_apply'=>$dis['review_status']??-1,
            'dis_brokerage'=>$dis['can_brokerage']??'0.00',
            'runn_brokerage'=>$running['info']['can_brokerage']??'0.00',
            'id'=>$user->id??'',
            'invit_code'=>$user->id??'',
            'create_time'=>$user->create_time??'',
            'coupon'=>$coupon??0,
        ];
        $data = array_merge($data,$running);
        return commonApi::message('ok',true,$data);
    }

    /**
     * 更新分销关系
     * @param $userid
     * @return array
     */
    public function updateDis($userid)
    {
        $model = self::find()->where(['id'=>$userid])->one();
        if (!$model){
            return commonApi::message('暂无用户',false);
        }
        TransformApi::tx(function ()use ($model){
            if ($model->second_level){//存在上级
                $second = self::find()->where(['id'=>$model->second_level])->one();
                if ($second){
                    $second->sub_num += 1;
                    $model->one_level = $second->second_level;
                    $second->save();
                    if ($second->second_level){
                        $one = self::find()->where(['id'=>$second->second_level])->one();
                        if ($one){
                            $model->top_level = $one->second_level;
                        }
                    }
                }
            }
            $model->dis_status = 1;
            if ($model->save()!==false){
                return commonApi::message('更新成功');
            }
            throw new Exception('更新失败');
        },$result);
        return $result;
    }

    /**
     * 获取下级用户列表
     * @param $userid 用户id
     * @param $page 页数
     * @return array
     */
    public function disUser($userid,$page)
    {
        $query = self::find()->where(['second_level'=>$userid])
            ->select(['id as userid','headimgurl','info','phone','second_brokerage as brokerage','sub_num','create_time','dis_status'])
            ->orderBy(['create_time'=>SORT_DESC]);
        $data = PageApi::apiPage($query,$page);
        $arr = [];
        foreach ($data['data'] as $key=>$datum){
            $info = json_decode($datum['info'],true);
            $datum['nickname'] = $info['nickName']??'';
            $exist_sub = 0;
            if ($datum['sub_num']>0){
                $exist_sub = 1;
            }
            $arr[] = [
                'userid'=>$datum['userid'],
                'headimgurl'=>$datum['headimgurl'],
                'nickname'=>$datum['nickname'],
                'phone'=>$datum['phone'],
                'brokerage'=>$datum['brokerage'],
                'sub_num'=>$datum['sub_num'],
                'create_time'=>$datum['create_time'],
                'dis_status'=>$datum['dis_status'],
                'exist_sub'=>$exist_sub,
            ];
        }
        $data['data'] = $arr;
        return commonApi::message('ok',true,$data);
    }

    /**
     * 获取分销数据
     * @param $userid
     * @return array
     */
    public function disStatistics($userid)
    {
        $query = self::find()->where(['second_level'=>$userid])->select(['sum(sub_num) as sub_num','count(*) as num']);
        $day_query = clone $query;
        $total_query = clone $query;
        //人数
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        $day = $day_query->andWhere(['between','create_time',$start,$end])->asArray()->one();
        $total = $total_query->asArray()->one();
        $day['sub_num'] = $day['sub_num']??0;
        $total['sub_num'] = $total['sub_num']??0;
        $day['num'] = $day['num']??0;
        $total['num'] = $total['num']??0;
        //佣金
        $orderQuery = Order::find()->where(['order_status'=>5,'refund_status'=>0]);
        $dayOderQuery = clone $orderQuery;
        $totalOderQuery = clone $orderQuery;
        $ady_one_brokerage = $dayOderQuery->andWhere(['between','settl_time',$start,$end])->andWhere(['one_level'=>$userid])->sum('one_brokerage');
        $ady_second_brokerage = $dayOderQuery->andWhere(['between','settl_time',$start,$end])->andWhere(['second_level'=>$userid])->sum('second_brokerage');
        $one_brokerage = $totalOderQuery->andWhere(['one_level'=>$userid])->sum('one_brokerage');
        $second_brokerage = $totalOderQuery->andWhere(['second_level'=>$userid])->sum('second_brokerage');
        $arr = [
            'day_people'=>$day['sub_num']+$day['num'],
            'total_people'=>$total['sub_num']+$total['num'],
            'day_brokerage'=>$ady_one_brokerage+$ady_second_brokerage,
            'total_brokerage'=>$one_brokerage+$second_brokerage,
        ];
        return commonApi::message('ok',true,$arr);
    }

    /**
     * 操作佣金
     * @param $userid 用户id
     * @param $fund_type 资金类型
     * @param $add_sub 加减
     * @param $amount 金额
     * @param $use 用途
     * @param $remarks 备注
     * @return array|mixed
     */
    public function operBrokerage($userid,$fund_type,$add_sub,$amount,$use,$remarks='')
    {
        if ($fund_type==1){//跑腿佣金
            $model = Running::findOne(['userid'=>$userid]);
        }elseif ($fund_type==2){//分销佣金
            $model = User::findOne(['id'=>$userid]);
        }elseif ($fund_type==3){//校区佣金
            $model = Campus::findOne(['payment_userid'=>$userid]);
        }else{
            return commonApi::message('完善佣金操作',false);
        }
        if ($add_sub==1){//加
            $front = $model->can_brokerage;
            $model->can_brokerage += $amount;
            $model->total_brokerage += $amount;
        }else{//减
            if ($model->can_brokerage<$amount){
                return commonApi::message('余额不足',false);
            }
            $front = $model->can_brokerage;
            $model->can_brokerage -= $amount;
        }
        TransformApi::tx(function ()use ($model,$userid,$fund_type,$add_sub,$front,$amount,$use,$remarks){
            if ($model->save()){
                Water::add($userid,$fund_type,$add_sub,$front,$amount,$use,$remarks);
                return commonApi::message('ok');
            }
            throw new Exception('错误');
        },$result);
        return $result;
    }

    /**
     * 获取海报
     * @param $userid
     * @return array
     */
    public function poster($userid)
    {
        $model = self::findOne($userid);
        if (!$model->poster){
            $config = System::applets();
            $wx = new WeChatApi($config);
            $result = $wx->appletsQr('pages/index/index',$userid);
            if (!$result['success']){
                return $result;
            }
            if ($model&&!$model->poster){
                $upload = new UploadApi();
                $res = $upload->oss($result['data']['img'],'qxyp_poster_'.$userid);
                if (!$res){
                    return commonApi::message('上传海报失败',false);
                }
                $model->poster = $res;
                $model->poster_time = date('Y-m-d H:i:s');
                $model->save();
            }
        }
        return commonApi::message('ok',true,['poster'=>$model->poster]);
    }
}
